package cc.cix.gt.org.controller;

import cc.cix.gt.common.constant.StringConstant;
import cc.cix.gt.common.entity.ResultPage;
import cc.cix.gt.org.dto.query.QueryRoleReq;
import cc.cix.gt.org.dto.request.RoleReq;
import cc.cix.gt.org.entity.Role;
import cc.cix.gt.org.service.IRoleService;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @author cix
 */
@Api(tags = "角色管理")
@Slf4j
@Validated
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/role")
public class RoleController {

    private final IRoleService roleService;

    @ApiOperation("角色列表")
    @GetMapping
    public ResultPage<Role> listRole(QueryRoleReq dto) {
        return roleService.listRole(dto);
    }

    @ApiOperation("角色详情")
    @GetMapping("/{id}")
    public Role getRole(@PathVariable String id) {
        return roleService.getById(id);
    }

    @ApiOperation("添加角色")
    @PreAuthorize("hasAuthority('role:add')")
    @PostMapping
    public void addRole(@Valid @RequestBody RoleReq dto) {
        Role role = BeanUtil.toBean(dto, Role.class);
        roleService.createRole(role);
    }

    @ApiOperation("删除角色")
    @PreAuthorize("hasAuthority('role:delete')")
    @DeleteMapping("/{roleIds}")
    public void deleteRoles(@PathVariable String roleIds) {
        List<String> ids = StrUtil.splitTrim(roleIds, StringConstant.COMMA);
        roleService.deleteRoleByIds(ids);
    }

    @ApiOperation("更新角色")
    @PreAuthorize("hasAuthority('role:update')")
    @PutMapping
    public void updateRole(@Valid @RequestBody RoleReq dto) {
        Role role = BeanUtil.toBean(dto, Role.class);
        roleService.updateRole(role);
    }

}
